package top.yqingyu.httpserver.db;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import top.yqingyu.common.qydata.DataMap;
import top.yqingyu.common.utils.DecryptAES;
import top.yqingyu.common.utils.YamlUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.httpserver.db.DB
 * @description
 * @createTime 2022年11月04日 23:23:00
 */
public class DB {

    static final HikariDataSource HIKARI_DATA_SOURCE;

    static {
        HIKARI_DATA_SOURCE = initDataSource();
    }


    /**
     * @author YYJ
     * @description 创建数据源数据源
     */
    private static HikariDataSource initDataSource() {
        DataMap yamlUtil = YamlUtil.loadYaml("server-cfg", YamlUtil.LoadType.BOTH).getCfgData();
        DataMap cfg = yamlUtil.getNotNUllData("server-cfg.yml");
        DataMap dataMap = cfg.getDataMap("database");
        HikariConfig hikariConfig = new HikariConfig();
        String poolName = dataMap.getString("poolName");
        String url = dataMap.getString("url");
        String username = dataMap.getString("username");
        String pwd = dataMap.getString("pwd");
        String driver = dataMap.getString("driver");
        long connectionTimeout = dataMap.getLong("connectionTimeout");
        int miniIdle = dataMap.getIntValue("miniIdle");
        int maxPoolSize = dataMap.getIntValue("maxPoolSize");
        String connectionTestQuery = dataMap.getString("connectionTestQuery");
        long idle$timeout = dataMap.getLong("idle$timeout");
        long max$lifetime = dataMap.getLong("max$lifetime");
        hikariConfig.setPoolName(poolName);
        hikariConfig.setJdbcUrl(url);
        hikariConfig.setUsername(DecryptAES.decryptBase64Key(username));
        hikariConfig.setPassword(DecryptAES.decryptBase64Key(pwd));
        hikariConfig.setDriverClassName(driver);
        hikariConfig.setConnectionTimeout(connectionTimeout);
        hikariConfig.setMinimumIdle(miniIdle);
        hikariConfig.setMaximumPoolSize(maxPoolSize);
        hikariConfig.setConnectionInitSql(connectionTestQuery);
        hikariConfig.setConnectionTestQuery(connectionTestQuery);
        hikariConfig.setIdleTimeout(idle$timeout);
        hikariConfig.setMaxLifetime(max$lifetime);
        hikariConfig.setAutoCommit(true);
        return new HikariDataSource(hikariConfig);
    }

    public static Connection getConnection() throws SQLException {
        return HIKARI_DATA_SOURCE.getConnection();
    }


    public static boolean executeSql(String sql) throws SQLException {
        Connection connection = getConnection();
        connection.setAutoCommit(true);
        Statement statement = connection.createStatement();
        boolean execute = statement.execute(sql);
        statement.close();
        connection.close();
        return execute;
    }
}
